using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using Microsoft.SharePoint.Search.Query;
using System.Xml;

namespace CKS.EBE.WebControls
{
    public class SearchResults : CKS.EBE.WebControls.XmlBasedControl
    {
        protected override System.Xml.XmlDocument BuildDocument()
        {
            try
            {
                FullTextSqlQuery ftq = new FullTextSqlQuery(Web.Site);
                ftq.QueryText = "select rank, title, author, created, path, HitHighlightedSummary from scope() where freetext('" + Page.Request["k"] + "') AND Site='" + Web.Url + "' ORDER BY Rank desc --";


                KeywordQuery kq = new KeywordQuery(Web.Site);
                kq.KeywordInclusion = KeywordInclusion.AllKeywords;
                kq.QueryText = Page.Request["k"];// +" site: " + Web.Url;
                //kq.SelectProperties.Add("Title");
                //kq.SelectProperties.Add("Body");
                ftq.ResultTypes = ResultType.RelevantResults;
                ftq.RowLimit = 10;
                //kq.SiteContext = new Uri(Web.Url);
                ResultTableCollection oTables = ftq.Execute();

                XmlDocument oResults = new XmlDocument();
                oResults.LoadXml("<rows/>");

                foreach (ResultTable oTable in oTables)
                {
                    while (oTable.Read())
                    {
                        XmlElement oResult = oResults.CreateElement("row");
                        oResults.DocumentElement.AppendChild(oResult);
                        for (int c = 0; c < oTable.FieldCount; c++)
                        {
                            XmlElement oField = oResults.CreateElement(oTable.GetName(c));
                            oField.InnerText = oTable.GetString(c);
                            oResult.AppendChild(oField);
                        }
                    }
                }

                return oResults;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                return null;
            }
        }
    }
}
